package com.winning.sx.microframework.common.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.sx.microframework.common.config.Config;
import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


/**
 * Desc: 工具类 Time: 20:44:55
 */
public class FileTools {
    public static String saveImage(String path, String imgData) throws Exception {
        Map<String, Object> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String realPath = Config.uploadDiskPath + "/" + path;
            String imgStr = imgData;
            if (imgStr == null)
                throw new Exception("参数为空");

            String imgCode[] = imgStr.split(",");
            BASE64Decoder decoder = new BASE64Decoder();

            //Base64解码
            byte[] b = decoder.decodeBuffer(imgCode[1]);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//调整异常数据
                    b[i] += 256;
                }
            }
            //生成图片
            mkdir(realPath);
            String filePath = "/" + generateFileName() + "." + imgCode[0].substring(imgCode[0].indexOf("/") + 1, imgCode[0].indexOf(";"));
            OutputStream out = new FileOutputStream(realPath + filePath);
            out.write(b);
            out.flush();
            out.close();
            return Config.downloadPath + path + filePath;
        } catch (Exception e) {
            throw new Exception("保存图片失败：" + e.getMessage());
        }

    }

    private static String generateFileName() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        int code = (int) (Math.random() * 9000 + 1000);
        return sdf.format(new Date()) + code + "";
    }

    public static void mkdir(String path) {
        File file = new File(path);
        //如果文件夹不存在则创建
        if (!file.exists() && !file.isDirectory()) {
            System.out.println("//不存在");
            if (file.mkdirs()) {
                System.out.println("//已创建");
            } else {
                System.out.println("//无法创建");
            }
        } else {
            System.out.println("//目录存在");
        }
    }
}